package cn.xiaoliu.hrm.userdetails;

import cn.xiaoliu.hrm.domain.LoginUser;
import cn.xiaoliu.hrm.domain.Permission;
import cn.xiaoliu.hrm.feign.UserInfoFeignClients;
import cn.xiaoliu.hrm.mapper.LoginUserMapper;
import cn.xiaoliu.hrm.util.AjaxResult;
import cn.xiaoliu.hrm.util.ValidUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class HrmUserDetailsService implements UserDetailsService{
    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private UserInfoFeignClients userInfoFeignClients;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //校验username不能为空
        ValidUtils.assertNotNull(username,"用户名不能为空" );
        //根据用户名查询
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        loginUser = loginUserMapper.selectOne(loginUser);
        //校验一下这个loginuser是不是空
        ValidUtils.assertNotNull(loginUser,"该用户不存在" );

        //调用System服务查询用户其他的基本信息 封装好，以便其他地方使用
        AjaxResult result = userInfoFeignClients.findUserInfo(loginUser.getId());
        if (result.isSuccess()){
            Object resultObj = result.getResultObj();
            /**
             * 将用户的基本信息放入一个地方
             * 1.放在上下文中  利用name字段，将用户的信息放在name字段上;
             * 其他服务在获取name字段的时候，实际上获取的就是用户的基本信息
             * 2.放在redis中（推荐使用）
             */
            String key = "userinfo"+username;
            System.out.println(resultObj);
            redisTemplate.opsForValue().set(key,resultObj);
        }


        //查询用户的权限
        List<Permission> permissions = loginUserMapper.findPermissionsByUserId(loginUser.getId());
        //封装权限
        ArrayList<SimpleGrantedAuthority> authors = new ArrayList<>();
        permissions.stream().forEach(permission -> {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getSn());
            authors.add(authority);
        });
        User user = new User(loginUser.getUsername(),loginUser.getPassword(),authors);
        return user;
    }
}
